<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/7
 * Time: 11:23
 */
namespace App\Service\Api;

use Illuminate\Support\Facades\Redis;
use App\Constant\RedisKeyConstant;
use App\Http\Model\Mysql\HotKeywordModel;

class HistoryService extends BaseService
{
    const MAX_SEARCH_LENGTH =   10;

    /**
     * 获取用户搜索记录
     * @return array
     */
    public function historyList()
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];
        $result     =   Redis::LRANGE(RedisKeyConstant::USER_SEARCH_HISTORY . $user_id, 0, self::MAX_SEARCH_LENGTH - 1);
        return [true, $result];
    }

    /**
     * 用户搜索记录保存
     * @param string $search_word 搜索词汇
     * @return array
     */
    public function historySearch(string $search_word)
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];
        $list_key   =   RedisKeyConstant::USER_SEARCH_HISTORY . $user_id;
        //删除重复搜索词
        Redis::LREM($list_key, 0, $search_word);

        $result     =   Redis::LPUSH($list_key, $search_word);

        //只保留10个搜索词
        Redis::LTRIM($list_key, 0, self::MAX_SEARCH_LENGTH - 1);
        if ($result) {
            return [true, $result];
        } else {
            return [false, '保存失败'];
        }
    }

    /**
     * 搜索记录删除
     * @return array
     */
    public function historyClear()
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];
        $result     =   Redis::DEL(RedisKeyConstant::USER_SEARCH_HISTORY . $user_id);
        return [true, $result];
    }

}
